package org.squabble.util;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

	public static final List<GrantedAuthority> NO_AUTHORITIES = Collections.emptyList();

	
	public static boolean userHasAuthority(String authority) {
		Collection<GrantedAuthority> authorities = getUserAuthorities();

		for (GrantedAuthority grantedAuthority : authorities) {
			if (authority.equals(grantedAuthority.getAuthority())) {
				return true;
			}
		}

		return false;
	}

    private static Collection<GrantedAuthority> getUserAuthorities() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth == null || auth.getAuthorities() == null) {
            return NO_AUTHORITIES;
        }

        return auth.getAuthorities();
    }
	
	
}
